# -*- coding: utf-8 -*-
# F7帮助面板（界面）
# @Time    ： 2022/1/8  16:38
# @Auther  ： 徐良
# File     :  f7HelpPanel.py

import re
from PySide6.QtCore import Signal, Qt
from PySide6.QtWidgets import QMainWindow, QApplication, QMessageBox
from PySide6.QtGui import QAction
from mesParts.components.ui.f7HelpPanelUI import Ui_MainWindow
# from share.dataFactory import DataFactory
# from share.funPublic import getSWO
from share.dataFactory import DataFactory
from share.makeTree import MakeTree


class F7HelpPanel(QMainWindow, Ui_MainWindow):
    """
    f7带浏览和搜索界面的帮助面板
    """
    F7HelpRetSignal = Signal(dict)  # F7帮助面板发出的返回信号，dict = self.retMap

    def __init__(self, pDict):
        super(F7HelpPanel, self).__init__()
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.setupUi(self)
        self.retMap = {}  # 返回值字典
        self.nameCbo.addItem('编码')
        self.nameCbo.addItem('名称')

        self.baseDbType = pDict['baseDbType']
        self.treeSql = pDict['treeSql']
        self.simpleTableSql = pDict['simpleTableSql']
        self.detailedTableSql = pDict['detailedTableSql']

        self.treeLabel = pDict['treeLabel']
        self.simpleLabel = pDict['simpleLabel']
        self.detailLabel = pDict['detailLabel']

        self.simpleColumnList = pDict["simpleColumnList"]
        self.detailColumnList = pDict["detailColumnList"]

        self.simpleHideList = pDict['simpleHideList']
        self.detailHideList = pDict['detailHideList']

        self.getFieldList = pDict["getFieldList"]
        self.getTypeList = pDict["fieldTypeList"]
        self.retFieldList = pDict["retFieldList"]

        self.toolBar.actionTriggered[QAction].connect(self.processtrigger)
        self.setWindowModality(Qt.ApplicationModal)  # 设置为模态
        # 读数据
        self.readSimpleData(self.simpleTableSql)
        self.readDetailData(self.detailedTableSql)
        # 设置标签
        self.setLabel()
        # 建树 通过线程建树
        self.buildTree()

        self.treeWidget.itemDoubleClicked.connect(self.itemDBClick)

        # self.searchEdit.returnPressed.connect(self.on_searchBtn_clicked)

        self.simpleTableView.doubleClicked.connect(self.onSimpleTableViewDbClicked)
        self.detailTableView.doubleClicked.connect(self.onDetailTableViewDbClicked)

    def readSimpleData(self, sql):
        """
        读简表数据
        :return:
        """
        # 浏览界面tableView
        self.simpleModel = DataFactory.getQueryModelForSql(sql, self.baseDbType)
        self.simpleTableView.setModel(self.simpleModel)
        self.simpleTableView.setHeader(self.simpleColumnList)
        self.simpleTableView.setHideColumnForPosition(self.simpleHideList)

    def readDetailData(self, sql):
        """
        读明细数据
        :param sql:
        :return:
        """
        # 搜索界面
        self.detailModel = DataFactory.getQueryModelForSql(sql, self.baseDbType)
        self.detailTableView.setModel(self.detailModel)
        self.detailTableView.setHeader(self.detailColumnList)
        self.detailTableView.setHideColumnForPosition(self.detailHideList)

    def setLabel(self):
        """
        设置标签
        :return:
        """
        self.lbl_tree.setText(self.treeLabel)
        self.lbl_simpleTable.setText(self.simpleLabel)
        self.lbl_detailTable.setText(self.detailLabel)

    def buildTree(self):
        """
        建树
        :return:
        """
        # 建树
        makeTree = MakeTree(self.treeSql, self.treeWidget, self.baseDbType)
        makeTree.createTree()
        self.treeWidget.setColumnWidth(0, 150)

    # 左树选择变化
    def itemDBClick(self, it, col):

        fnumber = it.text(0)
        sLen = str(len(fnumber))
        print(sLen)


    def makeRet(self, model, index):
        retValueList = []
        for f in self.getFieldList:
            v = model.record(index.row()).value(f)
            retValueList.append(v)
        self.retMap = {'retFieldList': self.retFieldList,
                       'retValueList': retValueList, 'fieldTypeList': self.getTypeList,
                       'sender': self.sender,
                       'ret': True,
                       'obj': self.obj,
                       'work': self.work,
                       'index': self.index}

        self.F7PanelRetSignal.emit(self.retMap)
        self.close()

    def onSimpleTableViewDbClicked(self, index):
        """
        # 简略表双击事件
        :return:
        """
        if index.isValid():
            print(index.row())
        # self.makeRet(self.simpleModel, index)

    def onDetailTableViewDbClicked(self, index):
        """
        # 详细表双击事件
        :return:
        """
        if index.isValid():
            print(index.row())

            # self.makeRet(self.detailedModel, index)

    def processtrigger(self, q):

        if (q.text() == '浏览'):
            self.stackedWidget.setCurrentIndex(0)
        elif (q.text() == '搜索'):
            self.stackedWidget.setCurrentIndex(1)
        elif (q.text() == '刷新'):
            self.readSimpleData(self.simpleTableSql)
            self.readDetailData(self.detailedTableSql)
            self.searchEdit.setText('')
        elif (q.text() == '关闭'):
            self.close()

    @Signal
    def on_cleanBtn_clicked(self):
        print('abc')
        # self.searchEdit.setText('')
        # 重新读数据库记录
        # self.detailedModel.setQuery(self.detailedSql, BIO_DB)
    #
    # @Signal()
    # def on_searchBtn_clicked(self):
    #     ss = self.nameCbo.currentText().strip()
    #     scondi = self.searchEdit.text().strip()
    #     swo = getSWO(self.detailedSql)
    #     s = swo['s']
    #     w = swo['w']
    #     o = swo['o']
    #
    #     # fnumber和name 之前要考虑是否需要加别名
    #     r = re.search(r'a\.\w{2,}', s)
    #     condi = " like '%" + scondi + "%'"
    #
    #     if r != None:  # 有别名
    #         if ss == '名称':
    #             fn = 'a.fname'
    #         else:
    #             fn = 'a.fnumber'
    #     else:
    #         if ss == '名称':
    #             fn = 'fname'
    #         else:
    #             fn = 'fnumber'
    #
    #     condi = fn + condi
    #     # 改变 where 条件
    #     if w == '':  # 原始的SQL语句中没有where 条件
    #         w = "where " + condi
    #     else:
    #         w = w + " and " + condi
    #
    #     sql = swo['s'] + ' ' + w + ' ' + swo['o']
    #     self.detailedModel.setQuery(sql, BIO_DB)

    def setInfo(self):
        self.lbl_item.setText('{name}信息'.format(name=self.browseDiscription))
        self.lbl_infoitem.setText('内容：共计{count}条记录'.format(count=self.simpleModel.rowCount()))

        self.lbl_infoicitem.setText('{name}内容,共计{count}条记录'.
                                    format(name=self.searchDiscription, count=self.detailedModel.rowCount()))
        self.statusBar().showMessage('就绪')

    def closeEvent(self, event):
        event.accept()
        return
        if not self.mythread.isFinished():
            reply = QMessageBox.question(self,
                                         'MES',
                                         "正在读取数据，是否要退出？",
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.mythread.quit()
                event.accept()

            else:
                event.ignore()

        if bool(self.retMap) == False:  # 如果未选择任何条目，则返回空内容字典
            # ret:False 无返回数据
            self.retMap = {'retFieldList': self.retFieldList,
                           'retValueList': [],
                           'fieldTypeList': self.getTypeList,
                           'sender': self.sender,
                           'ret': False,
                           'obj': self.obj,
                           'work': self.work,
                           'index': self.index
                           }
            self.F7PanelRetSignal.emit(self.retMap)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    dic = {}
    window = F7HelpPanel(dic)
    window.show()
    sys.exit(app.exec())
